<!--  单位管理  -->

<template>
  <div>
    <div class="m_contentBox">
      <a-card :bordered="false">
        <div class="m_aCardBox">
          <!-- 查询区域 -->
          <div class="tabBox">
            <div class="table-page-search-wrapper">
              <a-form layout="inline" @keyup.enter.native="searchQuery">
                <a-row :gutter="24">
                  <a-col :span="6">
                    <a-form-model-item label="单位分组">
                      <a-select placeholder="请选择" optionFilterProp="label" v-model="queryParam.parentId"
                                showSearch allowClear>
                        <a-select-option v-for="item in unitGroupList" :key="item.id" :label="item.groupName"
                                         :value="item.id">{{ item.groupName }}
                        </a-select-option>
                      </a-select>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="6">
                    <a-form-model-item label="单位名称">
                      <a-input placeholder="请输入" v-model="queryParam.unitCode" allowClear></a-input>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="6">
                  </a-col>
                  <a-col :span="6">
                    <a-form-model-item label="">
                      <div style="width: 100%;display: flex;justify-content: flex-end;">
                        <a-button type="primary" @click="searchQuery()">查询</a-button>
                        <a-button @click="searchReset()" style="margin-left: 8px">重置</a-button>
                      </div>
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </a-form>
            </div>
          </div>
          <!-- 查询区域-END -->
          <!-- table区域-begin -->
          <div class="cardBox">
            <div class="m_mb24">
              <a-button @click="openAddUnitGroupDrawer" type="primary" icon="plus">新增分组</a-button>
              <a-button @click="handleAdd" type="primary" icon="plus" style="margin-left: 8px">新增单位</a-button>
            </div>
            <a-table
                ref="table"
                size="middle"
                :scroll="{x:true}"
                bordered
                rowKey="id"
                :columns="columns"
                :dataSource="dataSource"
                :pagination="ipagination"
                :loading="loading"
                :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
                class="j-table-force-nowrap"
                @change="handleTableChange">

              <template slot="htmlSlot" slot-scope="text">
                <div v-html="text"></div>
              </template>
              <template slot="imgSlot" slot-scope="text,record">
                <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
                <img v-else :src="getImgView(text)" :preview="record.id" height="25px" alt=""
                     style="max-width:80px;font-size: 12px;font-style: italic;"/>
              </template>
              <template slot="fileSlot" slot-scope="text">
                <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
                <a-button
                    v-else
                    :ghost="true"
                    type="primary"
                    icon="download"
                    size="small"
                    @click="downloadFile(text)">
                  下载
                </a-button>
              </template>

              <span slot="action" slot-scope="text, record">
          <a @click="handleDetail(record)">详情</a>

          <a-divider type="vertical"/>

          <a @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical"/>

          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
          </a-popconfirm>
        </span>

              <!-- 展示单位换算的插槽 -->
              <span slot="convert" slot-scope="text, record">
          <!-- 循环的是包含单位换算对象的数组 -->
          <div v-for="(item,index) in record.cyEmissionUnitConvert">
            1 {{ item.sourceUnit }} = {{ item.value }} {{ item.targetUnit }}
          </div>
        </span>
            </a-table>
          </div>
          <!-- 新增分组的抽屉 -->
          <a-drawer
              :title="title"
              :width="800"
              placement="right"
              :closable="false"
              @close="onClose"
              destroyOnClose
              :visible="addUnitGroupVisible"
          >
            <!-- 新增分组抽屉中的table表格，封装为组件 -->
            <cy-unit-group-drawer v-show="addUnitGroupVisible"></cy-unit-group-drawer>
          </a-drawer>
          <!-- 单位管理详情和编辑抽屉 -->

          <a-drawer
              :title="title"
              :width="700"
              placement="right"
              :closable="false"
              @close="onClose"
              destroyOnClose
              :visible="unitDetailVisible"
          >
            <!-- 用于单位详情和单位编辑中的表单 -->
            <!-- detailDataSource为表单数据来源,使得父子组件可以双向使用: 父组件查询出数据传递给子组件,子组件修改完数据后重新返回给父组件 -->
            <!-- forwardList正向单位转换数组,contraryList反向单位转换数组,子组件将俩个数组传递回来,使父组件后续封装数据进行修改操作 -->
            <cy-unit-detail-form ref='unitdetailForm' :detailDataSource="detailDataSource" :detailFlag="detailFlag"
                                 :forwardList='forwardList' :contraryList='contraryList'
                                 @getAllConvert='getAllConvert'></cy-unit-detail-form>


            <span style="float:right">
      <a-button type="primary" @click="onClose()">关闭</a-button>
      <a-button type="primary" v-show="detailFlag != 1" @click="editUnit()" style="margin-left: 8px">提交</a-button>
    </span>
          </a-drawer>
          <!-- 系统生成时的新增单位抽屉组件 -->
          <cy-emission-unit-modal ref="modalForm" @ok="modalFormOk"></cy-emission-unit-modal>
        </div>
      </a-card>
    </div>
  </div>

</template>

<script>

import '@/assets/less/TableExpand.less'
import {mixinDevice} from '@/utils/mixin'
import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import CyEmissionUnitModal from './modules/CyEmissionUnitModal'
import {deleteAction, getAction, postAction} from '../../../api/manage'
import CyUnitGroupDrawer from './modules/CyUnitGroupDrawer.vue'
import CyUnitDetailForm from './modules/CyUnitDetailForm.vue'

export default {
  name: 'CyEmissionUnitList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    CyEmissionUnitModal,
    CyUnitGroupDrawer,
    CyUnitDetailForm
  },
  data() {
    return {
      description: '碳排因子单位管理页面',
      // 表头
      columns: [
        {
          title: '单位分组',
          align: "center",
          dataIndex: 'parentName'
        },

        {
          title: '单位名称',
          align: "center",
          dataIndex: 'unitCode'
        },
        {
          title: '单位换算',
          align: "center",
          dataIndex: 'cyEmissionUnitConvert',
          scopedSlots: {customRender: 'convert'}
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: "center",
          fixed: "right",
          width: 147,
          scopedSlots: {customRender: 'action'}
        }
      ],
      url: {
        // 单位分页列白查询
        list: "/emission/factor/cyEmissionUnit/list",
        // 单位分组查询
        unitGroup: "/CyFactorUnitGroup/cyFactorUnitGroup/list",
        //单位删除
        delete: "/emission/factor/cyEmissionUnit/delete",
        deleteBatch: "/CyEmissionUnit/cyEmissionUnit/deleteBatch",
        exportXlsUrl: "/CyEmissionUnit/cyEmissionUnit/exportXls",
        importExcelUrl: "CyEmissionUnit/cyEmissionUnit/importExcel",
        // 查询单位详情
        queryById: "/emission/factor/cyEmissionUnit/queryById",
        // 编辑单位
        editUnit: "/emission/factor/cyEmissionUnit/edit",


      },
      dictOptions: {},
      superFieldList: [],
      // 单位分组集合
      unitGroupList: [],
      // 新增单位分组
      addUnitGroupVisible: false,
      // 单位详情于编辑
      unitDetailVisible: false,
      // 单位详情数据来源
      detailDataSource: {},
      // 详情于编辑的区分标致
      detailFlag: null,
      // 正向单位转换数组
      forwardList: [],
      // 反向单位转换数组
      contraryList: [],
      // 单位编辑对象（用于调编辑接口，构造传参对象）
      editParam: {},
      backObj: {}
    }
  },
  created() {
    this.getSuperFieldList();
    //调用查询单位分组方法
    this.searchGroup();
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    },
  },
  methods: {
    initDictConfig() {
    },
    getSuperFieldList() {
      let fieldList = [];
      fieldList.push({type: 'string', value: 'unitName', text: '单位名称', dictCode: ''})
      fieldList.push({type: 'string', value: 'unitCode', text: '单位', dictCode: ''})
      fieldList.push({type: 'string', value: 'parentId', text: '父类ID', dictCode: ''})
      fieldList.push({type: 'string', value: 'organizationId', text: '组织ID', dictCode: ''})
      fieldList.push({type: 'string', value: 'deptId', text: '部门ID', dictCode: ''})
      this.superFieldList = fieldList
    },
    //单位分组分页列表查询
    searchGroup() {
      getAction(this.url.unitGroup).then(res => {
        this.unitGroupList = res.result.records
      })
    },
    // 打开新增单位分组的抽屉
    openAddUnitGroupDrawer() {
      this.addUnitGroupVisible = true;
      this.searchGroup();
    },
    // 统一的抽屉关闭方法
    onClose() {
      this.addUnitGroupVisible = false;
      this.unitDetailVisible = false;
      this.searchGroup();
    },
    //查询对应单位对象的数据详情
    handleDetail(record) {
      getAction(this.url.queryById, {id: record.id}).then(res => {
        console.log(res)
        this.detailDataSource = res.result;
        this.unitDetailVisible = true;
        this.detailFlag = 1;
      })
    },
    //编辑对应单位对象的数据详情
    handleEdit(record) {
      getAction(this.url.queryById, {id: record.id}).then(res => {
        console.log(res)
        this.detailDataSource = res.result;
        this.unitDetailVisible = true;
        this.detailFlag = 0;
      })
    },
    getAllConvert(e1, e2) {
      console.log('getAllConvert', e1, e2);
      this.forwardList = e1;
      this.contraryList = e2;

      // 将单位的主体对象赋值给编辑参数对象
      this.editParam = this.detailDataSource.cyEmissionUnit;
      this.detailDataSource.cyEmissionUnitConvert = [];

      // todo 转换数组为空了，没有值    查询单位的下来列表框需要修改


      // 将正向转换对象数组和反向转换对象数组中的数据统一到一个数组当中

      for (let i = 0; i < this.forwardList.length; i++) {
        this.detailDataSource.cyEmissionUnitConvert.push(this.forwardList[i])
      }

      for (let i = 0; i < this.contraryList.length; i++) {
        this.detailDataSource.cyEmissionUnitConvert.push(this.contraryList[i])
      }

      //如果正向和反向数组都为空，则设置合并的数组为空数组，此时后台就不进行插入操作
      if (this.forwardList.length < 1 && this.contraryList.length < 1) {
        this.editParam.unitConvertList = [];
      } else {
        // 否则就将数据放入编辑对象中，对单位的转换对象进行修改操作
        this.editParam.unitConvertList = this.detailDataSource.cyEmissionUnitConvert
      }


      console.log(this.editParam)

      // 调用接口进行编辑操作
      postAction(this.url.editUnit, this.editParam).then(res => {
        if (res.code == 200) {
          this.$message.success(res.message)
          this.unitDetailVisible = false;
          this.searchQuery()
        }
      })
    },
    // 编辑单位
    editUnit() {
      console.log('editUnit', this.$refs.unitdetailForm);
      this.$refs.unitdetailForm.submitqqqq()

    }
  }
}
</script>
<style lang="less" scoped>
@import '~@assets/less/common.less';

/deep/ .ant-card-body {
  background: #F5F8F7;
}

.tabBox {
  padding: 24px 24px 0;
  background: #FFFFFF;
  border-radius: 3px;
}

.cardBox {
  margin-top: 24px;
  padding: 24px;
  background: #FFFFFF;
  border-radius: 3px;
}

</style>